﻿// <copyright file="OclEnsureRelated.cs" company="Codeplex project Eco.Contrib"> 
// The MIT License (MIT) 
// </copyright> 
// <author>Peter Buchmann</author> 

namespace Eco.Contrib
{
    using System;
    using Eco.ObjectRepresentation;
    using Eco.Ocl.Support;

    /// <summary>
    /// OCL function EnsureRelated
    /// </summary>
    [EcoOclOperation(typeof(OclEnsureRelated), true)]
    public class OclEnsureRelated : OclOperationBase
    {
        /// <summary>
        /// Implementation of OCL funktion EnsureRelated
        /// </summary>
        /// <param name="oclParameters">The parameters.</param>
        public override void Evaluate(IOclOperationParameters oclParameters)
        {
            if (oclParameters == null)
            {
                throw new EcoContribException("Parameter is null");
            }
            
            IElementCollection coll = Support.GetAsList(oclParameters.Values[0]);
            string association = Support.GetAsString(oclParameters.Values[1]);
            try
            {
                (coll as IObjectList).EnsureRelatedObjects(association);
            }
            catch (Exception)
            {
                throw new EcoContribException("Association " + association + " does not exist");
            }

            oclParameters.Result.SetReferenceElement(coll);
        }

        /// <summary>
        /// Initialisation of OCL function EnsureRelated
        /// </summary>
        protected override void Init()
        {
            IOclType[] parameter = new IOclType[] { Support.ListType, Support.StringType };
            InternalInit("EnsureRelated", parameter, OclResultTypeDeduceMethod.TypeOfSource);
        }
    }
}
